<?php

namespace Our;

/**
 * 控制器抽象类
 */
abstract class Controller_AbstractAdmin extends \Our\Controller_Abstract {

    /**
     * 初始化方法，检查用户是否有登录
     */
    public function init() {
        \Yaf\Dispatcher::getInstance()->disableView();
    }

    /**
     * 获取搜索语句条件转换成sql的where条件，暂时都用=
     * 
     * @param $options 参数
     * @return array
     */
    protected function _getWhere($options = array()) {
        if (!$this->_getParam('where')) {
            return array();
        }
        //解析获取的where参数字符串
        $params = $this->_analyseWhere();

        $where = array();
        foreach ($params as $key => $value) {
            //如果有设置like字段
            if (!empty($options["like"]) && in_array($key, $options["like"])) {
                $where['`' . $key . '` like ?'] = '%' . rawurldecode($value) . '%';
                continue;
            }
            $where['`' . $key . '` = ?'] = $value;
        }

        return $where;
    }

    /**
     * 分析where
     * 
     * @return array
     */
    protected function _analyseWhere() {
        $params = array();
        $where  = $this->_getParam('where', null);
        if ($where === null) {
            return $params;
        }
        $where       = rawurldecode($where);
        $whereParams = explode('__iceup__', $where);
        $total       = count($whereParams);
        for ($i = 0; $i < $total; $i += 2) {
            $params[$whereParams[$i]] = $whereParams[$i + 1];
        }
        return $params;
    }

    /**
     * 转换数组参数为where值的字符串
     * 
     * @param array $array
     * @param boolean $isEcho
     * @return
     */
    public static function arrayToWhereString($array, $isEcho = true) {
        $tmp = array();
        foreach ($array as $key => $value) {
            $tmp[] = $key;
            $tmp[] = $value;
        }

        if (!$isEcho) {
            return implode('__iceup__', $tmp);
        }
        echo implode('__iceup__', $tmp);
    }

    /**
     * 获取排序条件
     */
    protected function _getOrder($default = array()) {
        $order = $this->_getParam('order_by', array());
        if (!$order) {
            return $default;
        }

        return array(rawurldecode($order));
    }

    /**
     * 获取搜索时的翻页的url
     * 
     * @return string
     */
    protected function _getBaseUrl() {
        $actionUrl = '';

        $i        = 1;
        $requests = array_filter(explode("/", $_SERVER['REQUEST_URI']));
        foreach ($requests as $v) {
            $actionUrl .= '/' . $v;
            $i++;
            if ($i > 3) {
                break;
            }
        }
        $actionUrl .= '/';


        $params = $this->_getParam();
        foreach ($params as $key => $value) {
            if ($key != 'page') {
                $actionUrl .= $key . '/' . rawurldecode($value) . '/';
            }
        }

        $actionUrl .= 'page/';
        return $actionUrl;
    }

    /**
     * 获取登录cookie
     * 
     * @return string
     */
    public function _getSso() {
        $sso = $this->getCookie("sso");
        if (!$sso) {
            $sso = $this->getRequest()->getParam('sso', '');
        }
        return $sso;
    }

    /**
     * 校验表单
     */
    protected function _validateForm($form) {
        if (!$form->validate()) {
            throw new \Exception(current($form->getMessages()), 110010);
        }
        return $form->getFieldValue();
    }

    /**
     * 输出错误的信息
     * 
     * @param string $message
     * @param int $errno 错误编号
     */
    protected function _echoErrorMessage($message, $errno = '1') {
        $return = array(
            'errno'  => $errno,
            'errmsg' => $message,
            'data'   => array()
        );
        if ($this->getRequest()->getQuery('is_jsonp')) {
            $callback = $this->getRequest()->getQuery('callback');
            if ($callback) {
                echo $callback . "(" . json_encode($return) . ")";
                exit();
                $this->getResponse()->setBody($callback . "(" . json_encode($return) . ")");
            }
        } else {
            $this->_displayJson($return);
        }
    }

    /**
     * 请求时输出成功的信息,并退出
     * 
     * @param string $message
     * @param array $data
     */
    protected function _echoSuccessMessage($message, $data = array()) {
        //检测fields字段，如果有设置则只传输相应的字段值
        $fields = array_filter(explode(',', $this->getRequest()->getParam('fields')));
        if ($fields) {
            foreach ($data as $k => $v) {
                if (!in_array($k, $fields)) {
                    unset($data[$k]);
                }
            }
        }

        $return = array(
            'errno'  => "0",
            'errmsg' => $message,
            'data'   => $data
        );

        //检测是否有jsonp的
        if ($this->getRequest()->getQuery('is_jsonp')) {
            $callback = $this->getRequest()->getQuery('callback');
            if ($callback) {
                echo $callback . "(" . json_encode($return) . ")";
                exit();
                $this->getResponse()->setBody($callback . "(" . json_encode($return) . ")");
            }
        } else {
            $this->_displayJson($return);
        }
    }

    /**
     * 输出json格式的数据
     * 
     * @param mixed $data
     */
    public function _displayJson($data) {
        \Yaf\Dispatcher::getInstance()->disableView();
        if (!$this->getRequest()->isCli()) {
            header('Content-Type: application/json; charset=utf-8');
        }
        echo json_encode($data);
        exit();
        $this->getResponse()->setBody(json_encode($data));
    }

    /**
     * 往视图层传递成功的消息
     * 
     * @param string $name
     * @param mix $value
     */
    protected function _assignSuccessMessage($message = "保存成功", $data = array()) {
        $result = array(
            'errno'  => '0',
            'errmsg' => $message,
            'data'   => $data,
        );
        $this->getView()->assign("result", $result);
    }

    /**
     * 往视图层传递失败的消息
     * 
     * @param string $name
     * @param mix $value
     */
    protected function _assignErrorMessage($message = "保存失败", $errno = 1, $data = array()) {
        $result = array(
            'errno'  => $errno,
            'errmsg' => $message,
            'data'   => $data,
        );
        $this->getView()->assign("result", $result);
    }

    /**
     * 将值传递到模板
     * 
     * @param string $name
     * @param mix $value
     */
    protected function _assign($name, $value) {
        $this->getView()->assign($name, $value);
    }

    /**
     * 获取get参数
     * 
     * @param type $key
     * @param type $defaultValue
     * @return type
     */
    protected function _getParam($key = null, $defaultValue = null) {
        if (!$key) {
            $params = $this->getRequest()->getParams();
            if ($defaultValue) {
                foreach ($defaultValue as $k => $v) {
                    if (empty($params[$k])) {
                        $params[$k] = $v;
                    }
                }
            }

            return $params;
        }

        return $this->getRequest()->getParam($key, $defaultValue);
    }

    /**
     * 变量是否Json格式
     * 
     * @param type $str
     * @return boolean
     */
    protected function _isJson($str) {
        @json_decode($str, true);
        if (json_last_error() == JSON_ERROR_NONE) {
            return true;
        } else {
            return false;
        }
    }

}
